package org.piera.diables;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.util.Log;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpGet;



public class ImageGallery extends Activity{
	
	private static final String SEARCH_ACTION = "com.jalbacar.restapi.SEARCH";
	private static final String SEARCH_URI = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=38cbf2db87cb435cc2d6e2db9fd07883&user_id=49122253@N08&format=json&nojsoncallback=1";
	final Adapter imageList = new ImageAdapter(this);
    private GridView gridview;
	
	private ProgressDialog progress;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.gallery);
        Typeface tf;
    	TextView tv;
    	
        tf = Typeface.createFromAsset(getAssets(), "fonts/BrushScriptStd.otf");
        tv = (TextView) findViewById(R.id.textView1);
        tv.setTypeface(tf);
        
        
        
        File dir = new File("/sdcard/diablesdepiera");
        
        
        try {
	        if (isConnected()) {
	            	HttpGet searchRequest;
					
						searchRequest = new HttpGet( new URI(SEARCH_URI));
					
	            	RestTask task = new RestTask(this,SEARCH_ACTION,"gallery");
	                task.execute(searchRequest);
	                //Display progress to the user
	                progress = ProgressDialog.show(this, "Galeria d'Imatges", "Carregant galeria...", true);
	        }else{
	            	
	         
		        if(dir.exists()) {
		        
			        if (dir.listFiles().length == 0){
			        	Log.v("Test", "empty folder");
			        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			        	builder.setMessage("Error carregant la galeria d'Imatges.")
			        	       .setCancelable(true)
			        	       .setTitle("ERROR")
			        	       .setIcon(drawable.ic_dialog_alert)
			        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			        	           public void onClick(DialogInterface dialog, int id) {
			        	        	   ImageGallery.this.finish();
			        	           }
			        	       });
			        	       
			        	AlertDialog alert = builder.create();
			        	alert.show();
			        	       	
			        }else{
			        	Log.v("Test", "not empty folder");
			        	gridview = (GridView) findViewById(R.id.gridview);
			        	gridview.setAdapter((ListAdapter) imageList);
			        	gridview.setOnItemClickListener(new OnItemClickListener() {
			                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {            	
			                    Intent intent = new Intent();
			                    intent.setAction(android.content.Intent.ACTION_VIEW);
			                    intent.setDataAndType(Uri.fromFile((File) imageList.getItem(position)),"image/*");                
			                    startActivity(intent);
			                }
			            });	        	
			        }
		        }else{
		        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		        	builder.setMessage("Error carregant la galeria d'Imatges.")
		        	       .setCancelable(true)
		        	       .setTitle("ERROR")
		        	       .setIcon(drawable.ic_dialog_alert)
		        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		        	           public void onClick(DialogInterface dialog, int id) {
		        	        	   ImageGallery.this.finish();
		        	           }
		        	       });
		        	       
		        	AlertDialog alert = builder.create();
		        	alert.show();
		        }
	        }
        
         } catch (URISyntaxException e) {
					// TODO Auto-generated catch block
        	 e.printStackTrace();
		 }
        
	 }
	 
	 public class ImageAdapter extends BaseAdapter {
	        private Context mContext;
	        private File dir = new File("/sdcard/diablesdepiera/");
	        private File[] mThumbIds = dir.listFiles();

	        public ImageAdapter(Context c) {
	            mContext = c;
	        }

	        public int getCount() {
	        	//File dir = new File("/sdcard/diablesdepiera/");
	 	        //File[] mThumbIds = dir.listFiles();
	            return mThumbIds.length;
	        }

	        public Object getItem(int position) {	        	 
	            return mThumbIds[position];
	        }

	        public long getItemId(int position) {
	            return 0;
	        }

	        // create a new ImageView for each item referenced by the Adapter
	        public View getView(int position, View convertView, ViewGroup parent) {
	            ImageView imageView;
	            if (convertView == null) {  // if it's not recycled, initialize some attributes
	                imageView = new ImageView(mContext);
	                imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
	                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	                imageView.setPadding(8, 8, 8, 8);
	            } else {
	                imageView = (ImageView) convertView;
	            }

	            imageView.setImageBitmap(BitmapFactory.decodeFile(mThumbIds[position].getAbsolutePath()));

	            return imageView;
	        }
	        
	                
	        

	    }
	 
	 @Override
	    public void onResume() {
	        super.onResume();
	    	this.registerReceiver(receiver, new IntentFilter(SEARCH_ACTION));
	    }
	    
	    @Override
	    public void onPause() {
	        super.onPause();
	    	unregisterReceiver(receiver);
	    }
	    
	    
	    //bradcast receiver
	    private BroadcastReceiver  receiver = new BroadcastReceiver() {
	    	public void onReceive(Context context, Intent intent) {
	    		if(progress != null) {
	    			progress.dismiss();
	    		}
	    		
	    		String response = intent.getStringExtra(RestTask.HTTP_RESPONSE);
	    			    		
	    		if (response.equals("ok")){
	    			gridview = (GridView) findViewById(R.id.gridview);
	    			gridview.setAdapter((ListAdapter) imageList);
		        	gridview.setOnItemClickListener(new OnItemClickListener() {
		                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {            	
		                    Intent intent = new Intent();
		                    intent.setAction(android.content.Intent.ACTION_VIEW);
		                    intent.setDataAndType(Uri.fromFile((File) imageList.getItem(position)),"image/*");                
		                    startActivity(intent);
		                }
		            });
	    		}else{
	    			AlertDialog.Builder builder = new AlertDialog.Builder(ImageGallery.this);
		        	builder.setMessage("Error descarregant imatges.")
		        	       .setCancelable(true)
		        	       .setTitle("ERROR")
		        	       .setIcon(drawable.ic_dialog_alert)
		        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		        	           public void onClick(DialogInterface dialog, int id) {
		        	        	   ImageGallery.this.finish();
		        	           }
		        	       });
		        	       
		        	AlertDialog alert = builder.create();
		        	alert.show();
	    			
	    		}	    		
	    	}
	    };
	    
	    public final boolean isConnected() {
			ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
			
			if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
			connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
			connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
			connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
				return true;
			} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) {
				return false;
			}
			
			return false;
		}

}
